<template>
  <el-dialog
    ref="dialogRef"
    v-model="dialogVisible"
    title="权限维护"
    width="750px"
    append-to-body
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" :inline="true" label-width="80px">
      <el-form-item label="权限名称" prop="menuName">
        <el-input v-model="formData.menuName" class="input" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item label="权限编码" prop="permissionCode">
        <el-input v-model="formData.permissionCode" placeholder="请输入权限编码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 权限列表 -->
    <el-table :data="permissionList" empty-text="暂无数据" style="width: 100%" border>
      <el-table-column label="权限名称" prop="menuName" align="center" />
      <el-table-column label="权限编码" prop="permissionCode" align="center" />
      <el-table-column label="操作" width="120px" align="center">
        <template #default="scope">
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="warning"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SysMenu } from '@/api/system/menuType'
import { menuApi } from '@/api'
import { MenuTypeEnum } from '@/enums/dictEnum'
import type { FormInstance } from 'element-plus'

// Props定义
interface Props {
  visible: boolean
  parentId: string
}

const props = defineProps<Props>()

// Emits定义
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
}>()

// 表单实例
const formRef = useTemplateRef<FormInstance>('formRef')

// 对话框引用
const dialogRef = ref()

// 对话框显示状态双向绑定
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 表单数据
const formData = reactive<SysMenu>({
  menuId: '',
  menuName: '',
  permissionCode: '',
  menuType: MenuTypeEnum.BUTTON,
  sort: 0,
  parentId: '-1'
})

// 表单校验规则
const rules = reactive({
  menuName: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }],
  permissionCode: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
})

// 权限列表
const permissionList = ref<SysMenu[]>([])

onMounted(() => {
  findPermissionList(props.parentId)
})

// 提交表单
const submitForm = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      saveMenu()
    }
  })
}

/** 删除权限点击事件 */
const handleDelete = (row: SysMenu) => {
  ElMessageBox.confirm('确认删除权限【' + row.menuName + '】吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      deleteMenu(row)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除权限'
      })
    })
}

// 关闭对话框
const closeDialog = () => {
  resetForm()
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  formData.menuId = ''
  formData.menuName = ''
  formData.permissionCode = ''
  formData.menuType = MenuTypeEnum.BUTTON
  formData.sort = 0
  formData.parentId = props.parentId || '-1'
}

/** 查询权限列表 */
const findPermissionList = (parentId: string) => {
  const queryParam = {
    parentId: parentId,
    menuType: MenuTypeEnum.BUTTON
  }
  menuApi
    .findMenuList(queryParam)
    .then((res: any) => {
      permissionList.value = res || []
    })
    .catch((err) => {
      ElMessage.error(err.message || '查询权限列表失败')
    })
}

/** 保存菜单 */
const saveMenu = () => {
  menuApi
    .saveMenu(formData)
    .then((res: any) => {
      findPermissionList(props.parentId)
      resetForm()
      ElMessage.success('保存权限成功')
    })
    .catch((err) => {
      ElMessage.error(err || '保存权限失败')
    })
}

/** 删除菜单 */
const deleteMenu = async (row: SysMenu) => {
  await menuApi
    .deleteMenu(row.menuId)
    .then((res: any) => {
      findPermissionList(props.parentId)
      ElMessage.success('删除权限成功')
    })
    .catch((err) => {
      ElMessage.error(err || '删除权限失败')
    })
}

// 监听parentId变化
watch(
  () => props.parentId,
  (newParentId) => {
    if (newParentId && newParentId !== '-1') {
      formData.parentId = newParentId
      findPermissionList(newParentId)
    }
  },
  { immediate: true }
)

// 提供方法给父组件调用
defineExpose({
  resetForm,
  dialogRef
})
</script>

<style scoped lang="less">
.input {
  width: 150px;
}
</style>
